<template>
    <d2-container>
        <div class="muse_filter_box">
            <!-- <el-form ref="filtersForm" :model="form">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item>
                            <el-input placeholder="账户" v-model="form.account"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-button type="primary" @click="filterSearch('filtersForm')">搜索</el-button>
                        <el-button @click="resetForm('filtersForm')">重置</el-button>
                    </el-col>
                </el-row>
            </el-form> -->
        </div>
        <div class="muse_table_box">
            <div class="muse_control_box">
                <el-button class="muse_float_left" type="primary" @click="addData">添加</el-button>
            </div>
            <el-table
                    :data="tableData"
                    style="width: 100%"
                    >
                <el-table-column prop="name" label="员工名称" width="150" />
                <el-table-column prop="cellphone" label="手机号" width="150" />
                <el-table-column prop="storeName" label="关联门店" />
                <el-table-column
                        fixed="right"
                        label="操作"
                        width="120">
                    <template slot-scope="scope">
                        <el-button @click="editRow(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="deleteRow(scope.row)" type="text" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    class="muse_pagination"
                    :background="true"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="paging.page"
                    :page-sizes="paging.pageSizeAry"
                    :page-size="paging.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="paging.total">
            </el-pagination>
        </div>

        <el-dialog title="添加员工" :visible="dialogDataByStaff"  :show-close="false">
                <el-form ref="detailForm" :model="detailForm" :rules="rules" label-width="80px">
                    <el-form-item label="员工姓名" prop="name">
                        <el-input placeholder="员工姓名" v-model="detailForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="cellphone">
                        <el-input placeholder="手机号" v-model="detailForm.cellphone"></el-input>
                    </el-form-item>
                    <el-form-item label="关联门店" required>
                        <el-input placeholder="关联门店" v-model="detailForm.storeName" readonly @focus="openStoreDialog"></el-input>
                    </el-form-item>
                </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="fnCloseDialogStaff">取 消</el-button>
                <el-button type="primary" @click="submitStaff">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="门店列表" :visible="dialogDataByStore"  :show-close="false">
            <el-table
                    :data="storeList"
                    ref="ref_table"
                    style="width: 100%"
                    @select="handleSelectionChange">
                <el-table-column fixed type="selection" width="55"/>
                <el-table-column prop="name" label="门店名称" width="150" />
                <el-table-column prop="brief" label="简介">
                    <template slot-scope="{row: {brief}}">
                        {{brief | subStr(10)}}
                    </template>
                </el-table-column>
                <el-table-column prop="label" label="门店标签">
                    <template slot-scope="{row: {label}}">
                        {{label.join(', ')}}
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间">
                    <template slot-scope="{row: {createdAt}}">
                        {{createdAt | date('YYYY-MM-DD HH:mm')}}
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    class="muse_pagination"
                    :background="true"
                    @size-change="handleSizeChangeByOne"
                    @current-change="handleCurrentChangeByOne"
                    :current-page="pagingByOne.page"
                    :page-sizes="pagingByOne.pageSizeAry"
                    :page-size="pagingByOne.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pagingByOne.total">
            </el-pagination>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogDataByStore = false">取 消</el-button>
                <el-button type="primary" @click="saveStoreToStaff">确 定</el-button>
            </span>
        </el-dialog>
    </d2-container>
</template>

<script>
  import tableMixin from '../mixins/tableMixin'
  import { getStoreList, changeStaff, deleteStaff, getStaffList, getOneStaff } from '@/api/admin'
  export default {
    name: 'storeList',
    mixins: [tableMixin],
    data () {
      return {
        form: {
        },
        storeAry: [],
        dialogDataByStaff: false,
        dialogDataByStore: false,
        detailForm: {
          name: '',
          cellphone: '',
          store: '',
          storeName: ''
        },
        rules: {
          name: [
            { required: true, message: '请输入员工姓名', trigger: 'blur' }
          ],
          cellphone: [
            { required: true, message: '请输入手机号', trigger: 'blur' }
          ]
        },
        pagingByOne: {
          page: 1,
          pageSize: 10,
          total: 0
        },
        storeList: []
      }
    },
    created () {
      this.getTableData()
    },
    methods: {
      // 获取列表数据
      async getTableData(value, type) {
        let params = {
          page: type === 'page'? (value ? value : this.paging.page) : this.paging.page,
          pageSize: type === 'pageSize'? (value ? value : this.paging.pageSize) : this.paging.pageSize
        }
        params = Object.assign({}, params, this.form)
        const { code, data: { total, currentPage, data, pageSize } } = await getStaffList(params)
        this.paging.total = total
        this.paging.pageSize = pageSize
        this.paging.page = currentPage
        this.tableData = data

        this.tableData.forEach(item => {
          const storeNames = []
          item.store.forEach(item2 => {
            storeNames.push(item2.name)
          })
          item['storeName'] = storeNames.join(', ')
        });
      },
      // 添加数据
      addData () {
        this.dialogDataByStaff = true
        this.detailForm = {}
      },
      // 提交员工信息
      async submitStaff () {
        if(this.detailForm._id) {
          this.detailForm['id'] = this.detailForm._id
        }
        const res = await changeStaff(this.detailForm)
        this.getTableData()
        this.fnCloseDialogStaff()
      },
      fnCloseDialogStaff() {
        this.dialogDataByStaff = false
        this.storeAry = []
      },
      // 编辑该行
      editRow(row) {
       this.dialogDataByStaff = true
       this.getOneStaff(row._id)
      },

      // 得到单个的详情数据 
      async getOneStaff(id) {
        const res = await getOneStaff({id: id})
        this.detailForm = res.data
        this.storeAry = this.detailForm.store
        const tempStore = this.detailForm.store
        this.detailForm.store = []
        this.detailForm['storeName'] = []
        tempStore.forEach(item => {
          this.detailForm.store.push(item._id)
          this.detailForm.storeName.push(item.name)
        })
      },

      // 删除该行
      deleteRow(row) {
        this.wrapConfirm(4).then(async () => {
          await deleteStaff({id: row._id})
          this.getTableData()
        }).catch(() => {})
      },


      handleSizeChangeByOne(value) {
        this.getStoreList(value, 'pageSize')
      },
      handleCurrentChangeByOne(value) {
        this.getStoreList(value, 'page')
      },
      // 获取门店列表数据
      async getStoreList(value, type) {
        let params = {
          page: type === 'page'? (value ? value : this.pagingByOne.page) : this.pagingByOne.page,
          pageSize: type === 'pageSize'? (value ? value : this.pagingByOne.pageSize) : this.pagingByOne.pageSize
        }
        params = Object.assign({}, params, this.form)
        const { code, data: { total, currentPage, data, pageSize } } = await getStoreList(params)
        this.pagingByOne.total = total
        this.pagingByOne.pageSize = pageSize
        this.pagingByOne.page = currentPage
        this.storeList = data

        const showAry = this.storeList.filter(item => {
            for(let i = 0; i < this.storeAry.length; i++) {
              if(item._id === this.storeAry[i]._id) {
                return true
              }
            }
          })

          this.$nextTick(() => {
            showAry.forEach(item => {
              this.$refs.ref_table.toggleRowSelection(item, true)
            })
          })
      },
      openStoreDialog () {
        this.dialogDataByStore = true
        this.pagingByOne.page = 1
        this.getStoreList()
      },
      // 关联门店
      handleSelectionChange(valueAry, value) {
        // this.storeAry = valueAry

        this.storeAry = this.storeAry.map(item => {
          return JSON.stringify(item)
        })
        if (this.storeAry.indexOf(JSON.stringify(value)) > -1) {
          this.storeAry.splice(this.storeAry.indexOf(JSON.stringify(value)), 1)
        } else {
          this.storeAry.push(JSON.stringify(value))
        }
        this.storeAry = this.storeAry.map(item => {
          return JSON.parse(item)
        })
      },
      saveStoreToStaff() {
        this.detailForm.store = []
        this.detailForm.storeName = []
        this.storeAry.forEach(item => {
          this.detailForm.store.push(item._id)
          this.detailForm.storeName.push(item.name)
        })
        this.detailForm.storeName = this.detailForm.storeName.join(', ')
        this.dialogDataByStore = false
      }
    }
  }
</script>

<style scoped>

</style>
